﻿var mxPlugin = window.mxPlugin || {};

$(document).ready(function () {
    mxPlugin.tableEditing = {
        init: function () {
            $("[mx-edit]").each(function (i, o) {
                $(o).click(function () {
                    mxPlugin.tableEditing.setEditMode(o, 1);
                    return false;
                });
            });
        },

        setEditMode: function (caller, mode) {
            var descriptor = $(caller).attr("mx-edit");
            descriptor = $.parseJSON(descriptor);
            var target = $(descriptor.target);

            if (target.attr("mx-editMode") == mode)
                return;

            target.attr("mx-editMode", mode);
            switch (mode) {
                case 0:
                    // edit mode cleared
                    target.data("mx-editSource").show();
                    $("#lnkSave", target).hide();
                    $("input", target).each(function (i, o) {
                        $(o).parent().html($(o).val());
                    });
                    break;
                case 1:
                    // edit mode is set
                    target.data("mx-editSource", $(caller));

                    $(caller).hide();
                    var t = $("tr", target)[0];

                    // construct new row with input fields
                    var s = "<tr class='editor'>";
                    $(descriptor.fields).each(function (i, o) {
                        s += "<td><input type='text' name='fldName' mx-field='" + o + "' id='fld" + o + "'/></td>";
                    });
                    for (var ix = descriptor.fields.length + 1; ix < t.cells.length; ix++) {
                        s += "<td />";
                    }
                    s += "<td><a id='lnkSave' href='#'>save</a></td></tr>";

                    // add row
                    $(t).after(s);
                    $("#lnkSave").click(function (event) {
                        var json = {};
                        $("input[mx-field]", $(event.target).parents("tr:first")).each(function (i, o) {
                            eval("json." + $(o).attr("mx-field") + "= \"" + $(o).val() + "\"");
                        });
                        mxPlugin.tableEditing.setEditMode(caller, 0);

                        var callback = null;
                        if (descriptor.callback)
                            callback = eval(descriptor.callback);
                        mxPlugin.async.post(descriptor.action, json, callback);
                    });
                    break;
            }
        }
    };

    mxPlugin.tableEditing.init();
});